package cn.edu.nju.ws.sview.servlets;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {
   private Logger logger = Logger.getLogger(LoginFilter.class.getName()) ;
    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		HttpServletRequest httprequest = (HttpServletRequest)request;
		String servletPath = httprequest.getServletPath();
		HttpServletResponse httpresponse = (HttpServletResponse)response;
		String from = httprequest.getScheme()+"://"+httprequest.getServerName()+":"+httprequest.getServerPort()+
			httprequest.getContextPath()+servletPath+"?"+httprequest.getQueryString();
		from  =URLEncoder.encode(from,"utf-8");
        if(httprequest.getSession().getAttribute("user")==null){
//        	httpresponse.sendRedirect("../login.jsp?from="+from) ;
        	httpresponse.sendRedirect("/sview/views/index.jsp") ;
        	return;
        }
        chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
